#!/usr/bin/env python

import wsgiref.handlers
from google.appengine.ext import webapp
from google.appengine.ext import db
from schema import *
import logging

class RankCollecter(webapp.RequestHandler):
  def post(self):
    
    computationid = long(self.request.get("computationid"))
    logging.debug("I'll count nodes for computation %i." % computationid)
    computation = RankComputation.get_by_id(computationid)
    iteration = computation.iteration_count
    logging.debug("This is iteration %i." % iteration)
    docid = checksum_from_key_name(self.request.get("docid"))
    amount = float(self.request.get("amount"))
    
    comp_ranks = DocumentRank.all().filter("computationid =", computationid)
    linked_rank = comp_ranks.filter("docid =", db.ByteString(docid)).get()
    
    if len(linked_rank.ranks) > iteration:
      logging.debug("This rank will be increased.")
      linked_rank.ranks[iteration] += amount
    else:
      logging.debug("This rank will be created")
      if iteration < 1:
        linked_rank.ranks = [amount]
      else:
        linked_rank.ranks.append(amount)
    linked_rank.put()


def main():
  logging.getLogger().setLevel(logging.DEBUG)
  wsgiref.handlers.CGIHandler().run(webapp.WSGIApplication([
    ('/distribute-rank', RankCollecter),
  ]))

if __name__ == '__main__':
  main()
